<?php
require_once "./config_root.php";
require_once "db_api.php";
date_default_timezone_set('Asia/Taipei') ;
while(1) 
{

	sleep(60);
	$now=time();
	$minute = date('i', $now);
	if($minute != "01")
		continue;
	$tp = date('YmdHi', $now);	//ex:201401021300
	echo "### LOOPING $tp ###\n";

	$allscene = getAllScene();
	foreach($allscene as $key => $scene) {
		$lat = $scene['lat'];
		$lon = $scene['lon'];
		$tbl = $scene['tbl'];
		$try = 0;

		
		 $url     = "http://api.openweathermap.org/data/2.5/weather?lat=$lat&lon=$lon";
again:
		 $weather= file_get_contents($url);
		if($weather === FALSE) {
			echo "[ERROR] get $tbl $url weather failed. do again after 5s";
			sleep(3);
			$try++;
			if($try < 3)  {
				goto again;
			}
		}
		$weather= json_decode($weather, true);
		if(!isset($weather['main']['temp'])) {
			$temperature= 0;
			$weather = "unknown";
		}
		else {
			$temperature= $weather['main']['temp'] - 273;
			$weather = $weather['weather'][0]['main'];
		}
		$url = "http://162.243.140.106/visitors/count_top_88210.php?place=$tbl";
		$webContent = file_get_contents($url);
		echo $scene['cname']." 溫度 $temperature 天氣 $weather $url ==> ".trim($webContent)."\n";
		$checkins = json_decode($webContent,true);
		$totalCheckins = $checkins['checkins'];
		insert_tbl_record($tbl, $tp, $weather, $temperature, $totalCheckins);
		


		
	}
	$now = time();
	$tp = date('YmdHi', $now);	//ex:201401021300
	print "ROUND END $tp ################\n";
	}
?>
